//
//  HomeWorkoutsRecordViewModel.swift
//  DaRings
//
//  Created by 尹琼 on 2022/11/11.
//

import UIKit
import RxSwift
import RxCocoa
import MYModule

open class HomeWorkoutsRecordViewModel: HomeBaseViewModel {
    
   
    public let UIReplay: BehaviorRelay<HomeWorkoutsRecordModel>
    
    
    public init(date: Date) {
        
        let dateStr = Self.dateStr(date: date)
        let UIModel = HomeWorkoutsRecordModel(date: dateStr, goalHour: 0, totalTimes: 0, totalCalories: 0, totalDuration: 0)
            
        UIReplay = BehaviorRelay<HomeWorkoutsRecordModel>(value: UIModel)
        
        super.init(cellType: .workoutsRecords)
        
        reloadData(date)
        
        
    }
    
    public override func reloadData(_ date: Date? = nil) {
        
        let UIModel = reloadMeasureState()
        
        guard let date = date else {
            return
        }

        let goalModel = ExerciseGoalsModel.currentGoal(weekDay: date.weekday)
        let goalTime = goalModel.exerciseTime

        var totalTimes = 0
        var totalCalories = 0
        var totalDuration = 0
        
        
        // 获取运动数据
        guard let trainModels =  [TrainingModel].deserialize(from: date), !trainModels.isEmpty else {
           
           let emptyModel = HomeWorkoutsRecordModel(date: "", goalHour: 0, totalTimes: 0, totalCalories: 0, totalDuration: 0)
           emptyModel.measureState = UIModel.measureState
           UIReplay.accept(emptyModel)
            return
        }
        
        let dateStr = Self.dateStr(date: date)

        trainModels.forEach {
            if $0.startTime > 0 {
                totalTimes = totalTimes + 1
            }
            totalCalories = totalCalories + $0.kcal
            totalDuration = totalDuration + $0.vaildTime
        }

        UIModel.date = dateStr
        UIModel.targetTime = goalTime
        UIModel.totalTimes = totalTimes
        UIModel.totalCalories = totalCalories
        UIModel.totalDuration = totalDuration/60

        UIReplay.accept(UIModel)
        
    }
    
    @discardableResult
    public func reloadMeasureState() ->HomeWorkoutsRecordModel {
        
        let model = UIReplay.value
        
        
        if BluetoothManager.shared.deviceState == .connected {
            
            model.measureState = (BluetoothManager.shared.measuring != .none || BluetoothManager.shared.isBatterycharging) ? .disabled : .normal
            
        } else {
            
            model.measureState = .disabled
        }
//        log.debug("是否在测量中\(BluetoothManager.shared.measuring)-------\(model.measureState)")
        return model
    }
    
 
}
